package cn.kgc.vue.filters;

import cn.hutool.json.JSONUtil;
import cn.kgc.vue.commons.JWTToken;
import cn.kgc.vue.commons.ResponseResult;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/4/10
 * @description 该过滤器主要实现对于token的验证  token合法 则直接放行
 */
@Slf4j
public class WebTokenFilter extends BasicHttpAuthenticationFilter {

    //  跨域请求的处理
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        // 跨域时会首先发送一个option请求，option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }

    // 该方法控制请求是否放行    true  直接放行
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // token校验通过  放行 true
        log.info("------------WebTokenFilter  isAccessAllowed---------------");

        PrintWriter writer = null;
        try {
            executeLogin(request, response);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // 响应结果给前端
            try {
                response.setContentType("application/json;charset=utf-8");
                writer = response.getWriter();
                String jsonStr = JSONUtil.toJsonStr(ResponseResult.error().message("token异常,请重新认证"));
                writer.write(jsonStr);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

        return false;
    }

    //  执行登录操作
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {

        // 通过请求对象 获取token
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("authorization");

        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token is empty");
        }

        // 认证主体
        Subject subject = getSubject(request, response);
        //  token   String    ->  AuthenticationToken
        JWTToken jwtToken = new JWTToken(token);
        subject.login(jwtToken);

        return true;
    }


}
